#include "drule.h"
#include "ui_drule.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QImage>

DRule::DRule(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DRule)
{
    ui->setupUi(this);
    connect(this->ui->buttonBox,SIGNAL(accepted()),SLOT(slotPreaccept()));
    connect(this->ui->btn_path,SIGNAL(clicked()),SLOT(slotPath()));
}

DRule::DRule(const QString &name, const QString &regexp, const QString &path, QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DRule)
{
    ui->setupUi(this);
    this->ui->le_name->setText(name);
    this->ui->le_regexp->setText(regexp);
    this->ui->le_path->setText(path);
    connect(this->ui->buttonBox,SIGNAL(accepted()),SLOT(slotPreaccept()));

}

DRule::~DRule()
{
    delete ui;
}

void DRule::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

QStringList DRule::getRule(){
    QStringList ret;
    ret.append(this->ui->le_name->text());
    ret.append(this->ui->le_regexp->text());
    ret.append(this->ui->le_path->text());
    return ret;
}

void DRule::slotPreaccept(){
    // проверяем валидность, ежели нет то ругаемся =)

    if(this->ui->le_name->text()==""){
        QMessageBox::warning(this,"TITLE","Error: Rule name is null");
    }else{
        if(this->ui->le_regexp->text()==""){
            QMessageBox::warning(this,"TITLE","Error: Rule regexp is null");
        }else{
            if(this->ui->le_path->text()==""){
                QMessageBox::warning(this,"TITLE","Error: Rule image is null");
            }else{
                QImage testImage;
                if(!testImage.load(this->ui->le_path->text())){
                    QMessageBox::warning(this,"TITLE","Error: Image loading failed");
                }else{
                    emit this->accept();
                }

            }
        }
    }
}

void DRule::slotPath(){
    // устанавливаем путь до картинки
    QFileDialog fd;
    fd.setFileMode(QFileDialog::ExistingFile);

    QString path=fd.getOpenFileName();
    // проверка пригодности изображения
        QImage testImage;
        if(testImage.load(path)){
            this->ui->le_path->setText(path);
        }else{
            QMessageBox::warning(this,"TITLE","Error: Image loading failed");
        }
}
